import React, {PureComponent} from 'react';
import {
  View,
  StyleSheet,
  Text,
  TextInput,
  Image,
  TouchableOpacity,
  ScrollView,
  KeyboardAvoidingView,
  Modal,
  TouchableWithoutFeedback,
  Dimensions,
} from 'react-native';
import I18n from 'react-native-i18n';
import {connect} from 'react-redux';
import BaseComponent from '../base/BaseComponent';
import {LinearButton, LinearBoardButton} from '../../components/Button';
import {sendCode, login, guestLogin} from '../../api/user';
import StorageManager, {
  USER_INFO,
  IS_FIRST_INSTALL,
  SELECTED_PHONE_AREA,
} from '../../storage';
import {updateUserInfo} from '../../redux/action';
import LinearGradient from 'react-native-linear-gradient';
import phoneAreas from '../../config/phoneArea';
import {Picker} from '@react-native-picker/picker';
import SharetraceModule from 'sharetrace-react-native';
import {Colors} from '../../styles/common';
import SplashScreen from 'react-native-splash-screen';
import DeviceInfo from '../../utils/device';
const {width, height} = Dimensions.get('window');

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFCB26',
  },
  loginForm: {
    textAlign: 'center',
    flexDirection: 'column',
    paddingLeft: 40,
    paddingRight: 40,
  },
  mobile: {
    backgroundColor: '#fff',
    height: 44,
    paddingLeft: 22,
    paddingRight: 22,
    borderRadius: 22,
    marginBottom: 20,
    flex: 1,
  },
  inviteCodeInput: {
    backgroundColor: '#fff',
    height: 44,
    paddingLeft: 22,
    paddingRight: 22,
    borderRadius: 22,
    marginBottom: 20,
    marginTop: 20,
  },
  codeContainer: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: 44,
  },
  code: {
    backgroundColor: '#fff',
    height: 44,
    paddingLeft: 22,
    paddingRight: 22,
    borderRadius: 22,
    flex: 1,
  },
  codeBtn: {
    marginLeft: 10,
    width: 80,
    height: 44,
    marginTop: 0,
  },
});

class LoginScreen extends BaseComponent {
  constructor(props) {
    super(props);

    this.state = {
      phone: '',
      code: '',
      timer: 60,
      inviteCode: '',
      timerStart: false,
      showInviteCode: false,
      loading: false,
      loginLoading: false,
      modalVisible: false,
      area: 1,
      selArea: 1,
      isChecked: 0,
      showLeadingView: false,
      guestLoginLoading: false,
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.getInstallChannel();

    SplashScreen.hide();

    console.log('===============');
    StorageManager.load(IS_FIRST_INSTALL).then((res) => {
      if (!res) {
        console.log('设置显示leading');
        this.setState({
          showLeadingView: true,
        });
      }
    });

    StorageManager.load(SELECTED_PHONE_AREA).then((res) => {
      if (res) {
        console.log('加载地区号码' + res);
        this.setState({
          area: Number(res),
          selArea: Number(res),
        });
      }
    });
  }

  getInstallChannel = () => {
    SharetraceModule.getInstallTrace((map) => {
      console.log('InstallTrace', map);
      // {"channel": "", "code": 200, "msg": "Success", "paramsData": "inviteCode=abcd"}
      if (map && map.paramsData) {
        let params = map.paramsData.split('&');
        for (var i = 0; i < params.length; i++) {
          var param = params[i].split('=');
          if (param[0] == 'inviteCode') {
            console.log(param[1]);
            this.setState({
              inviteCode: param[1],
            });
            break;
          }
        }
      }
    });
  };

  doLogin = () => {
    let {phone, code, inviteCode, selArea, isChecked} = this.state;

    if (phone.length == 0 || code.length == 0) {
      return;
    }

    if (!isChecked) {
      this._showAlert({content: 'please read and agree the user agreement'});
      return;
    }

    let param = {phone, code, area: selArea};
    if (this.state.showInviteCode && !inviteCode && inviteCode.length > 0) {
      param.inviteCode = inviteCode;
    }

    this.setState({
      loginLoading: true,
    });

    param.version = DeviceInfo.getVersion();
    param.platform = DeviceInfo.isIos() ? 'ios' : 'android';

    login(param)
      .then(async (res) => {
        this.setState({
          loginLoading: false,
        });
        console.log('登录结果', JSON.stringify(res));
        await this.props.updateUserInfo(res.data);
        StorageManager.save(USER_INFO, {
          ...res.data,
        });

        if (res.data.identify && res.data.identify.length != 0) {
          this.props.navigation.navigate('Home');
        } else {
          this.props.navigation.navigate('FillInformation');
        }
      })
      .catch((err) => {
        console.log(err);
        this.setState({
          loginLoading: false,
        });
        this._showAlert({content: err.msg || err});
      });
  };

  alertGuestLogin = () => {
    this._showAlert({
      content:
        'We will proveide you with a random account, but account data will not be saved',
      alertCancelPress: () => {},
      okTitle: 'Next',
      alertOkPress: () => {
        this.guestLogin();
      },
    });
  };

  guestLogin = () => {
    this.setState({
      guestLoginLoading: true,
    });

    guestLogin({
      version: DeviceInfo.getVersion(),
      platform: DeviceInfo.isIos() ? 'ios' : 'android',
    })
      .then(async (res) => {
        this.setState({
          guestLoginLoading: false,
        });
        console.log('登录结果', JSON.stringify(res));
        await this.props.updateUserInfo(res.data);
        StorageManager.save(USER_INFO, {
          ...res.data,
        });

        if (res.data.identify && res.data.identify.length != 0) {
          this.props.navigation.navigate('Home');
        } else {
          this.props.navigation.navigate('FillInformation');
        }
      })
      .catch((err) => {
        console.log(err);
        this.setState({
          guestLoginLoading: false,
        });
        this._showAlert({content: err.msg || err});
      });
  };

  sendCode = () => {
    if (
      this.state.timerStart ||
      this.state.loading ||
      this.state.phone.length == 0
    ) {
      return;
    }
    this.setState({
      loading: true,
    });

    sendCode({phone: this.state.phone, area: this.state.selArea})
      .then((res) => {
        this.setState({
          showInviteCode: res.data.showInviteCode == 1,
          loading: false,
        });
        this._startTimer();
      })
      .catch((err) => {
        this.setState({
          loading: false,
        });
        this._showAlert(err.msg || err);
      });
  };

  _startTimer() {
    this.interval && clearInterval(this.interval);
    this.setState({
      timerStart: true,
    });
    this.interval = setInterval(() => {
      this.setState({
        timer: this.state.timer - 1,
      });
      if (this.state.timer <= 0) {
        this.interval && clearInterval(this.interval);
        this.setState({
          timerStart: false,
          timer: 60,
        });
      }
    }, 1000);
  }

  start = () => {
    this.setState({
      showLeadingView: false,
    });

    StorageManager.save(IS_FIRST_INSTALL, new Date().valueOf());
  };

  renderComponent = () => {
    return (
      <LinearGradient
        start={{x: 1, y: 0}}
        end={{x: 1, y: 1}}
        colors={['#000', '#410056']}
        style={styles.container}>
        <KeyboardAvoidingView
          behavior={Platform.OS == 'ios' ? 'padding' : 'height'}
          style={{width: '100%', flex: 1}}>
          <ScrollView keyboardDismissMode style={styles.loginForm}>
            <Image
              style={{
                marginTop: '20%',
                marginBottom: 30,
                width: 200,
                height: 120,
                alignSelf: 'center',
              }}
              source={require('../../assets/login/logo.png')}
              resizeMode="contain"
            />
            <View style={{flexDirection: 'row'}}>
              <TouchableOpacity
                onPress={() => {
                  this.props.navigation.navigate('PhoneCode', {
                    selectCode: (code) => {
                      StorageManager.save(SELECTED_PHONE_AREA, code + '');

                      this.setState({
                        selArea: code,
                      });
                    },
                  });
                }}
                style={{
                  width: 80,
                  height: 44,
                  justifyContent: 'center',
                  alignItems: 'center',
                  backgroundColor: 'white',
                  borderRadius: 22,
                  marginRight: 10,
                }}>
                <Text style={{color: 'black'}}>{'+' + this.state.selArea}</Text>
              </TouchableOpacity>
              <TextInput
                style={styles.mobile}
                placeholder={I18n.t('login.mobile')}
                placeholderTextColor="#a1a1a1"
                keyboardType="phone-pad"
                onChangeText={(text) => {
                  this.setState({
                    phone: text,
                  });
                }}></TextInput>
            </View>
            <View style={styles.codeContainer}>
              <TextInput
                style={styles.code}
                placeholder={I18n.t('login.code')}
                placeholderTextColor="#a1a1a1"
                onChangeText={(text) => {
                  this.setState({
                    code: text,
                  });
                }}></TextInput>
              <LinearButton
                buttonStyle={styles.codeBtn}
                text={
                  this.state.timerStart
                    ? this.state.timer
                    : I18n.t('login.send')
                }
                loading={this.state.loading}
                onPress={this.sendCode}
                onChangeText={(text) => {
                  this.setState({
                    code: text,
                  });
                }}
              />
            </View>
            {this.state.showInviteCode ? (
              <TextInput
                style={styles.inviteCodeInput}
                value={this.state.inviteCode}
                placeholder={I18n.t('login.invite')}
                placeholderTextColor="#a1a1a1"
                keyboardType="phone-pad"
                onChangeText={(text) => {
                  this.setState({
                    inviteCode: text,
                  });
                }}></TextInput>
            ) : null}
            <View
              style={{
                flexDirection: 'row',
                alignItems: 'center',
                marginTop: 20,
              }}>
              <TouchableOpacity
                activeOpacity={0.8}
                onPress={() => {
                  this.setState({
                    isChecked: !this.state.isChecked,
                  });
                }}>
                <Image
                  style={{width: 20, height: 20, marginRight: 10}}
                  source={
                    this.state.isChecked
                      ? require('../../assets/common/checkbox.png')
                      : require('../../assets/common/checkbox-empty.png')
                  }
                />
              </TouchableOpacity>
              <Text numberOfLines={1} style={{color: 'white', marginRight: 4}}>
                i have read and agree the
              </Text>
              <TouchableOpacity
                onPress={() => {
                  this.props.navigation.navigate('Service', {
                    agree: () => {
                      this.setState({
                        isChecked: true,
                      });
                    },
                  });
                }}>
                <Text style={{color: '#C717ED'}}>agreement</Text>
              </TouchableOpacity>
            </View>
            <LinearButton
              text={I18n.t('login.login')}
              loading={this.state.loginLoading}
              onPress={this.doLogin}
            />
            <LinearBoardButton
              buttonStyle={{width: '100%'}}
              text={'Guest Login'}
              loading={this.state.guestLoginLoading}
              onPress={this.alertGuestLogin}></LinearBoardButton>
          </ScrollView>
        </KeyboardAvoidingView>
        <Modal
          animationType="fade"
          transparent
          visible={this.state.modalVisible}>
          <View
            style={{
              justifyContent: 'flex-end',
              flex: 1,
              backgroundColor: 'rgba(33,33,33,0.4)',
            }}>
            <TouchableWithoutFeedback
              onPress={() => {
                this.setState({
                  modalVisible: false,
                });
              }}>
              <View
                style={{
                  flex: 1,
                  width: '100%',
                }}></View>
            </TouchableWithoutFeedback>
            <View
              style={{
                backgroundColor: 'white',
                width: '100%',
                alignItems: 'center',
              }}>
              <Picker
                mode="dropdown"
                numberOfLines={5}
                style={{height: 200, width: '80%'}}
                selectedValue={this.state.area}
                onValueChange={(itemValue, itemIndex) => {
                  this.setState({
                    area: itemValue,
                  });
                }}>
                {phoneAreas.map((item, idx) => {
                  return (
                    <Picker.Item
                      label={`${item.en} +${item.code} `}
                      value={item.code}
                      key={(item, idx)}
                    />
                  );
                })}
              </Picker>
              <LinearButton
                buttonStyle={{width: 150, marginBottom: 20}}
                onPress={() => {
                  console.log('保存地区号码', this.state.area);
                  StorageManager.save(
                    SELECTED_PHONE_AREA,
                    this.state.area + '',
                  );

                  this.setState({
                    selArea: this.state.area,
                    modalVisible: false,
                  });
                }}
                text={'Sure'}
              />
            </View>
          </View>
        </Modal>
        <Modal
          animationType="fade"
          transparent
          visible={this.state.showLeadingView}>
          <ScrollView
            style={{flex: 1}}
            horizontal={true}
            alwaysBounceVertical={false}
            alwaysBounceHorizontal={false}
            showsHorizontalScrollIndicator={false}
            showsVerticalScrollIndicator={false}
            pagingEnabled>
            <View
              style={{
                height: height,
                width: width,
                position: 'relative',
                backgroundColor: Colors.backgroundColor_dark,
              }}>
              <Image
                style={{position: 'absolute', right: 0, top: 150}}
                source={require('../../assets/login/lh_1.png')}></Image>
              <Image
                style={{position: 'absolute', left: 50, bottom: '20%'}}
                width={50}
                height={50}
                source={require('../../assets/login/l_star.png')}></Image>
              <Image
                style={{position: 'absolute', right: 50, bottom: '40%'}}
                source={require('../../assets/login/l_star.png')}></Image>
              <View
                style={{
                  position: 'absolute',
                  left: 0,
                  top: '50%',
                  width: '60%',
                  height: 36,
                  backgroundColor: 'rgba(80,33,162,1)',
                  borderTopRightRadius: 18,
                  borderBottomRightRadius: 18,
                }}>
                <Text
                  style={{
                    lineHeight: 36,
                    color: 'white',
                    textAlign: 'center',
                    fontWeight: 'bold',
                    fontSize: 16,
                  }}>
                  Launching games
                </Text>
              </View>
              <View
                style={{
                  position: 'absolute',
                  width: '100%',
                  bottom: 50,
                  flexDirection: 'row',
                  justifyContent: 'center',
                }}>
                <View
                  style={{
                    width: 12,
                    height: 12,
                    backgroundColor: 'rgba(80,33,162,1)',
                    marginRight: 20,
                    borderRadius: 6,
                  }}></View>
                <View
                  style={{
                    width: 12,
                    height: 12,
                    backgroundColor: 'white',
                    marginRight: 20,
                    borderRadius: 6,
                  }}></View>
              </View>
            </View>
            <View
              style={{
                height: height,
                width: width,
                position: 'relative',
                backgroundColor: Colors.backgroundColor_dark,
              }}>
              <Image
                style={{position: 'absolute', right: 0, top: 150}}
                source={require('../../assets/login/lh_2.png')}></Image>
              <Image
                style={{position: 'absolute', left: 100, bottom: '20%'}}
                width={50}
                height={50}
                source={require('../../assets/login/l_star.png')}></Image>
              <Image
                style={{position: 'absolute', right: 50, bottom: '40%'}}
                source={require('../../assets/login/l_star.png')}></Image>
              <View
                style={{
                  position: 'absolute',
                  left: 0,
                  top: '50%',
                  width: '60%',
                  height: 36,
                  backgroundColor: 'rgba(80,33,162,1)',
                  borderTopRightRadius: 18,
                  borderBottomRightRadius: 18,
                }}>
                <Text
                  style={{
                    lineHeight: 36,
                    color: 'white',
                    textAlign: 'center',
                    fontWeight: 'bold',
                    fontSize: 16,
                  }}>
                  Share and communtiy
                </Text>
              </View>
              <View
                style={{
                  position: 'absolute',
                  width: '100%',
                  bottom: 50,
                  flexDirection: 'row',
                  justifyContent: 'center',
                }}>
                <View
                  style={{
                    width: 12,
                    height: 12,
                    backgroundColor: 'white',
                    marginRight: 20,
                    borderRadius: 6,
                  }}></View>
                <View
                  style={{
                    width: 12,
                    height: 12,
                    backgroundColor: 'rgba(80,33,162,1)',
                    marginRight: 20,
                    borderRadius: 6,
                  }}></View>
              </View>
              <LinearButton
                text="Start"
                buttonStyle={{
                  position: 'absolute',
                  width: 200,
                  left: '50%',
                  bottom: 80,
                  transform: [{translate: [-100, 0, 0]}],
                }}
                onPress={this.start}></LinearButton>
            </View>
          </ScrollView>
          <TouchableOpacity
            style={{position: 'absolute', right: 20, top: 100}}
            onPress={this.start}>
            <Text style={{color: 'white'}}>Skip</Text>
          </TouchableOpacity>
        </Modal>
      </LinearGradient>
    );
  };
}

const mapStateToProps = (state) => ({});

const mapDispatchToProps = (dispatch) => ({
  updateUserInfo: (item) => dispatch(updateUserInfo(item)),
});

export default connect(mapStateToProps, mapDispatchToProps)(LoginScreen);
